﻿using System;
using System.Web.UI;
using DevExpress.Web.ASPxUploadControl;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection conn;
    SqlDataReader read;
    string postingID = "";
    string date="";   
    const string UploadDirectory = "~/Student/UploadImages/";
    string pathRoot = "";
    string pathView = "";
    
    protected void Page_Load(object sender, EventArgs e)
    {        
        try
        {
            if (Session["Student"] == null)
                Response.Redirect("~/Student/HomePage.aspx");
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Institte_of_Fine_ArtsConnectionString"].ConnectionString);
            conn.Open();            
            postingID = Request.QueryString["id"].ToString();
            mulviwEditPostingDetails.ActiveViewIndex = 0;  
        }
        catch(NullReferenceException)
        {
            lbStatus.Text = "Please select competition!";
            mulviwEditPostingDetails.ActiveViewIndex = 1;
        }
        catch (Exception ex)
        {
            mulviwEditPostingDetails.ActiveViewIndex = 1;
            lbStatus.Text = ex.Message;
        }
        if (!IsPostBack)
        {
            retrieveData(postingID);
        }
    }

    private void retrieveData(string ID)
    {
        try
        {
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            SqlCommand comm = new SqlCommand("SELECT Painting, [Description], Uploaded_Date, Price FROM Posting WHERE PostingID='" + ID + "' AND StudentID='"+ Session["Student"] +"'", conn);
            SqlDataReader read = comm.ExecuteReader();
            while (read.Read())
            {
                previewImage.ImageUrl = read.GetString(0);
                memoDescription.Text = read.GetString(1);
                txtDate.Text = read.GetDateTime(2).ToLongDateString();
                txtPrice.Text = read.GetDecimal(3).ToString();
                Session["Date"] = read.GetDateTime(2).ToLongDateString();
            }
            conn.Close();
        }
        catch(Exception ex)
        {
            lbStatus.Text = ex.Message;
            mulviwEditPostingDetails.ActiveViewIndex = 1;
        }                   
        
    }
    
    protected void uplImage_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
    {
        e.CallbackData = SavePostedFile(e.UploadedFile);        
    }

    string SavePostedFile(UploadedFile uploadedFile)
    {               
        if (!uploadedFile.IsValid)
            return string.Empty;
        pathRoot = "StudentID_" + Session["Student"] + "_Date_" + Session["Date"] + ".jpg";
        pathView = "StudentID_" + Session["Student"] + "_Date_" + Session["Date"] + "_View.jpg";
        string fileName = Path.Combine(MapPath(UploadDirectory), pathView);
        string fileNameRoot = Path.Combine(MapPath(UploadDirectory), pathRoot);
        using (Image original = Image.FromStream(uploadedFile.FileContent))        
        using (Image thumbnail = Inscribe(original, 100))
        {
            SaveToJpeg(thumbnail, fileName);
            SaveToJpeg(original, fileNameRoot);            
        }
        return pathView;
    }

    public static Image Inscribe(Image image, int size)
    {
        return Inscribe(image, size, size);
    }

    public static Image Inscribe(Image image, int width, int height)
    {
        Bitmap result = new Bitmap(width, height);
        using (Graphics graphics = Graphics.FromImage(result))
        {
            double factor = 1.0 * width / image.Width;
            if (image.Height * factor < height)
                factor = 1.0 * height / image.Height;
            Size size = new Size((int)(width / factor), (int)(height / factor));
            Point sourceLocation = new Point((image.Width - size.Width) / 2, (image.Height - size.Height) / 2);

            SmoothGraphics(graphics);
            graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(sourceLocation, size), GraphicsUnit.Pixel);
        }
        return result;
    }

    static void SmoothGraphics(Graphics g)
    {
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    }

    public static void SaveToJpeg(Image image, Stream output)
    {
        image.Save(output, ImageFormat.Jpeg);
    }

    public static void SaveToJpeg(Image image, string fileName)
    {
        image.Save(fileName, ImageFormat.Jpeg);
    }


    protected void btUpdate_Click(object sender, EventArgs e)
    {
        try
        {            
            string fileNameView = "StudentID_" + Session["Student"] + "_Date_" + txtDate.Text + "_View.jpg";
            File.Delete(Server.MapPath(@"UploadImages/" + fileNameView));            
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            string strCommPosting = "UPDATE Posting SET Description='" + memoDescription.Text + "', Price='"+txtPrice.Text+"' WHERE PostingID ='"+ postingID +"'";
            SqlCommand commPosting = new SqlCommand(strCommPosting, conn);
            commPosting.ExecuteNonQuery();
            lbStatus.Text = "Update sucessly!";            
            mulviwEditPostingDetails.ActiveViewIndex = 1;            
        }        
        catch (Exception ex)
        {
            lbStatus.Text = "Error: " + ex.Message;
            mulviwEditPostingDetails.ActiveViewIndex = 1;
        } 
        
    }
}